/*
* @author suhong
* @date 2022/5/16 15:03
* @file user.js
* @说明  登录注册api处理函数
*/
//导入数据库
const exec = require('../../db/mysql_connect')
//导入包生成token jsonwebtoken
const jwt = require("jsonwebtoken")
const config=require('../../config/config')
//注册用户的处理函数
exports.regUser = (req, res) => {
    let username = req.body.username
    let password = req.body.password
    console.log(req.body)
    //查询语句
    let mysqlStr = `select * from blog_user where user_name='${username}'`
    //插入语句
    let insertStr = `insert into blog_user(user_name,user_password) values ('${username}','${password}')`
    if (!password || !username) {
        return res.bug("用户名或者密码不能为空")
    }
    exec(mysqlStr).then(result => {
        if (result.length>0) {
            res.bug("用户已经存在")
            return new Promise((resolve, reject) => {
            })
        }
        return result
    }).then(result => {
        exec(insertStr).then(value => {
            res.send({
                status: 0,
                message: '注册成功'
            })
        })
    }).catch(reason => {
        res.status(500).send({
            message: reason
        })
    })
}
//登录时候的处理函数
exports.login = (req, res) => {
    //获取用户输入的姓名和密码
    let username = req.body.username
    let password = req.body.password
    // res.send(req.body)
    let mysqlStr = `select * from blog_user where user_name='${username}'`
    // res.send(req.body)
    console.log(req.body)
    if (!password || !username) {
        return res.bug("用户名或者密码不能为空")
    }
    exec(mysqlStr).then(result => { //判断用户是否存在
        if (result.length<=0) throw "用户不存在"
        return result[0]
    }).then(result => {
        if (result.user_states !== 0) throw "用户状态异常"
        return result
        
    }).then(result => {
        if (result.user_password !== password)  throw "密码不正确"
        return result
    }).then(result=>{
        //生成token
        const tokenStr=jwt.sign({user:result.username,id:result.user_id},config.jwtKey,{expiresIn:'200s'})
        const token='Bearer '+tokenStr
        res.send({
            status: 0,
            message: 'success',
            user_id:result.user_id,
            token,
        })
    }).catch(reason => {
        res.bug(reason)
    })
}
